#include "my_client.h"
#include "QDebug"
#include "QHostAddress"
#include <QNetworkProxy>

my_client::my_client(QObject *parent) : QTcpSocket(parent)
{
    //    m_tcp = new QTcpSocket(parent);
    server_port = 7890;
    connect(this, &QTcpSocket::readyRead, this, &my_client::readyReadData);
    connect(this, &QTcpSocket::connected, this, &my_client::connect_cb);       // 连接客户端断开信号
    connect(this, &QTcpSocket::disconnected, this, &my_client::disconnect_cb); // 连接客户端断开信号
    this->setProxy(QNetworkProxy::NoProxy);                                    // 禁用代理服务器
}
void my_client::set_server_info(QString ip)
{
    server_ip = ip;
}
void my_client::connect_server(void)
{
    //    m_tcp->connectToHost(server_ip, server_port, QTcpSocket::ReadWrite);

    qDebug() << "host_ip:" << server_ip << "port:" << server_port << endl;
    // 连接服务器
    this->connectToHost(server_ip, server_port);
}

void my_client::sendData(QString data)
{
    // 数据做base64转码
    //    QByteArray base64 = data.toUtf8().toBase64();
    //    QString le;
    //    // 预留8字节保存长度
    //    le.sprintf("%08d", base64.size());
    //    // 拼接数据 报文长度+报文
    //    base64 = le.toUtf8() + base64;
    // 发送数据
    if (state() == QTcpSocket::ConnectedState)
    {
        this->write(data.toUtf8());
    }
}

void my_client::disconnect_cb(void)
{

    emit client_Disconnected(NULL);
    //    qDebug()<<"disconnect_cb";
}
void my_client::connect_cb(void)
{
    emit client_Connected(NULL);
    //    qDebug()<<"connect_cb";
}

void my_client::readyReadData()
{
    // 拿到发送信号的客户端指针，通过该指针读取数据
    emit client_recvsignal(this->readAll());
}
